//
//  BNRImageStore.m
//  Quiz
//
//  Created by YaoJacob on 15/11/5.
//  Copyright © 2015年 Roger. All rights reserved.
//

#import "BNRImageStore.h"
#import "BNRItemStore.h"

@interface BNRImageStore ()
@property(nonatomic, strong) NSMutableDictionary *dictionary;
@end

@implementation BNRImageStore
+(instancetype)sharedStore
{
    static BNRImageStore* sharedStore = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedStore = [[self alloc]initPrivate];
    });
    //    if (!sharedStore) {
    //        sharedStore = [[self alloc]initPrivate];
    //    }
    
    return sharedStore;
}

-(instancetype)init
{
    @throw [NSException exceptionWithName:@"Single" reason:@"use + [BNRImageStore sharedStore]" userInfo:nil];
    return nil;
}

-(instancetype)initPrivate
{
    self = [super init];
    if (self) {
        self.dictionary = [[NSMutableDictionary alloc]init];
        
        //内存过低警告
        NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
        [nc addObserver:self selector:@selector(clearImages:)
                   name:UIApplicationDidReceiveMemoryWarningNotification
                 object:nil];
    }
    return self;
}

-(void)setImage:(UIImage*)image forKey:(NSString*)key
{
    //    [self.dictionary setObject:image forKey:key];
    
    self.dictionary[key] = image;
    
    NSString* path = [[BNRItemStore sharedStore] itemArchivePathForFile:key];
    
    NSData* data = UIImagePNGRepresentation(image);
    
    [data writeToFile:path atomically:YES];
}

-(UIImage*)imageForKey:(NSString*)key
{
    //    return [self.dictionary objectForKey:key];
    UIImage * result = self.dictionary[key];
    if (!result) {
        NSString* path = [[BNRItemStore sharedStore] itemArchivePathForFile:key];
        
        result = [UIImage imageWithContentsOfFile:path];
        
        if (result) {
            self.dictionary[key] = result;
        }
        else
        {
            NSLog(@"error: unable to find.");
        }
    }
    
    return result;
}

-(void)deleteImageForKey:(NSString*)key
{
    if (!key) {
        return;
    }
    [self.dictionary removeObjectForKey:key];
    
    NSString* path = [[BNRItemStore sharedStore] itemArchivePathForFile:key];
    
    [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
}

#pragma 内存过低
-(void)clearImages:(NSNotification *)note
{
    NSLog(@"%lu images out of cache", (unsigned long)[self.dictionary count]);
    
    [self.dictionary removeAllObjects];
}
@end
